//子游戏内 预制体读取管理工具

//主预制体onDestroy时请调用releaseAll();
const { ccclass, property } = cc._decorator;

@ccclass
class BasePrefabMgrByHall {

    _Prefabs = null;
    /**
     * 
     * @param path 资源路径
     * @param cb 回调
     * @param type 类型 默认预制体
     */
    loadRes(path: string, cb: Function, type = cc.Prefab) {

        cc.log("已经加载的预制体", this._Prefabs)

        if (!this._Prefabs) {
            this._Prefabs = {};
        }
        if (this._Prefabs[path]) {
            if (cb) {
                cb(this._Prefabs[path]);
            }
            return;
        }
        cc.loader.loadRes(
            path,
            type,
            // (completedCount, totalCount, ...item) => {
            //     if (item[0].content)
            //         cc.log("动态读取资源进程:", completedCount, "/", totalCount, item[0].content._name);
            //     else
            //         cc.log("动态读取资源进程:", completedCount, "-----/", totalCount, item);
            // },
            (err, prefab) => {
                if (err) {
                    cc.error("动态加载失败:\nPath:", path, "\nerror:", err)
                    return;
                }
                //base中的资源不释放
                if (!this._checkIsBase(path)) {
                    this._Prefabs[path] = prefab;
                }

                if (cb) {
                    cb(prefab);
                }
            }
        );
    }
    _checkIsBase(path: string) {
        let paths = path.split("Base/BaseModule");
        if (paths.length > 1) {
            return true;
        }
        return false;
    }
    /**
     * 
     * 释放资源但是不释放Base里的资源
     * @param path 资源路径 
     * 
     */
    releaseRes(path) {
        if (this._checkIsBase(path)) {
            return;
        }
        if (this._Prefabs && this._Prefabs[path]) {
            cc.log("释放资源", path)
            cc.loader.releaseRes(path);
            delete this._Prefabs[path];
        }
    }
    /**
     * 
     */
    releaseAll() {
        if (this._Prefabs)
            for (const key in this._Prefabs) {
                this.releaseRes(key);
            }
    }
}
export default new BasePrefabMgrByHall();